library(here)
library(tidyverse)

load(here("Analysis", "analysis_sameDA.rda"), verbose = TRUE)
load(here("Data", "sameDAdat.rda"), verbose = TRUE)

pdf(file = here("Figures_Tables", "coefplot_SameDA.pdf"), width = 8, height = 2)
par(oma = rep(0, 4), mar = c(4, 1, 2, 1), mgp = c(3, .5, 0), xpd = NA)
oldmai <- par("mai")
newmai <- oldmai
newmai[2] <- max(strwidth(row.names(res1SameDA[1:2, ]), units = "inches")) + .1
par(mai = newmai)
nmods <- nrow(res1SameDA[1:2, ])
theylim <- range(c(0, as.vector(res1SameDA[1:2, ])[is.finite(as.vector(res1SameDA[1:2, ]))]))
plot(theylim, c(1, nmods),
  type = "n", axes = FALSE, ylab = "",
  xlab = "Effect of 1 Unit Difference in Perceptions of Visible Minorities in Local Community \n (+/- 95% CI)"
)
segments(res1SameDA[1:2, "ci1"], 1:nmods, res1SameDA[1:2, "ci2"], 1:nmods)
points(res1SameDA[1:2, "Estimate"], 1:nmods, pch = 19)
abline(v = 0, lwd = .5, col = gray(.7))
axis(1, line = .5)
axis(2, at = 1:nmods, labels = row.names(res1SameDA[1:2, ]), las = 1)
par(mai = oldmai)
dev.off()


pdf(file = here("Figures_Tables", "coefplot_mlm_SameDA.pdf"), width = 8, height = 2)
par(oma = rep(0, 4), mar = c(4, 1, 2, 1), mgp = c(3, .5, 0), xpd = NA)
oldmai <- par("mai")
newmai <- oldmai
newmai[2] <- max(strwidth(row.names(res1SameDA_mlm[1:2, ]), units = "inches")) + .1
par(mai = newmai)
nmods <- nrow(res1SameDA_mlm[1:2, ])
theylim <- range(c(0, as.vector(res1SameDA_mlm[1:2, ])[is.finite(as.vector(res1SameDA_mlm[1:2, ]))]))
plot(theylim, c(1, nmods),
  type = "n", axes = FALSE, ylab = "",
  xlab = "Effect of 1 Unit Difference in Perceptions of Visible Minorities in Local Community \n (+/- 95% CI)"
)
segments(res1SameDA_mlm[1:2, "ci1"], 1:nmods, res1SameDA_mlm[1:2, "ci2"], 1:nmods)
points(res1SameDA_mlm[1:2, "Estimate"], 1:nmods, pch = 19)
abline(v = 0, lwd = .5, col = gray(.7))
axis(1, line = .5)
axis(2, at = 1:nmods, labels = row.names(res1SameDA_mlm[1:2, ]), las = 1)
par(mai = oldmai)
dev.off()



## sameDAdat %>%
##   arrange(dauid, vm.community.subj) %>%
##   select(dauid, vm.community.subj, perc_rank)
##
## table(table(sameDAdat$dauid))
##
## da_level_dat <- sameDAdat %>%
##   group_by(dauid) %>%
##   summarize(
##     "Social cohesion" = mean(social.capital01[perc_rank == max(perc_rank)]) -
##       mean(social.capital01[perc_rank < max(perc_rank)]),
##     "Community efficacy" = mean(community.resp01[perc_rank == max(perc_rank)]) -
##       mean(community.resp01[perc_rank < max(perc_rank)])
##   )
##
## da_long <- pivot_longer(data = da_level_dat, cols = c("Social cohesion", "Community efficacy"))
##
## g_sc <- ggplot(data = da_long, aes(x = name, y = value)) +
##   geom_boxplot() +
##   geom_jitter(width = 0) +
##   geom_hline(yintercept = 0) +
##   stat_summary(fun = mean, color = "black", shape = "triangle") +
##   ylab("") +
##   xlab("") +
##   theme_minimal()
## g_sc
##
## ggsave(g_sc, file = "pair_diffs_sameDAviewDA.pdf", width = 6, height = 6)




system("touch Figures_Tables/sameDA_figures.done")
